package cn.apestar.common.chat.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.message.BasicNameValuePair;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import cn.apestar.common.chat.Chat;
import cn.apestar.common.chat.enums.HuanXianError;
import cn.apestar.common.chat.enums.MessageWTType;
import cn.apestar.common.chat.exception.BaseException;
import cn.apestar.common.chat.model.EasemobMedel;
import cn.apestar.common.chat.model.RegUser;
import cn.apestar.common.chat.util.HttpUtil;
import cn.apestar.common.huanxin.Base64CoderUtil;

/**
 * 环信API
 * @author lvh
 */
public class ChatHuanXian implements Chat {

    private EasemobMedel easemobMedel;

    public ChatHuanXian(EasemobMedel easemobMedel) {
        this.easemobMedel = easemobMedel;
    }

    @Override
    public String getToken() {

        String clientId = easemobMedel.getHuanxinClientId();
        String clientSecret = easemobMedel.getHuanxinClientSecret();
        String token = getAppToken(clientId, clientSecret);
        Map map = JSONObject.parseObject(token, HashMap.class);
        String key = "Bearer " + map.get("access_token").toString();
        return key;
    }

    /**
     * 获取APP管理员Token
     */
    public String getAppToken(String clientId, String clientSecret) {

        JSONObject param = new JSONObject();
        try {
            param.put("grant_type", easemobMedel.getHuanxinGrantType());
            param.put("client_id", clientId);
            param.put("client_secret", clientSecret);
            return HttpUtil.executionPost(easemobMedel.getHuanxinUrl() + "/token", param, null);
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

    /**
     * 注册IM用户[单个]
     * @param username 当前用户
     * @param nickname 别名
     * @throws IOException
     */
    @Override
    public boolean regUser(String username, String password, String nickname) {

        JSONObject param = new JSONObject();
        param.put("username", username);
        param.put("password", password);
        param.put("nickname", nickname);
        try {
            return HttpUtil.getResult(HttpUtil.executionPost(easemobMedel.getHuanxinUrl() + "/users", param, getToken()));
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

    /**
     * 注册IM用户[多个]
     * @param username 当前用户
     * @param nickname 别名
     * @throws IOException
     */
    @Override
    public void regPlUser(List<RegUser> user) {

        try {
            HttpUtil.executionPost(easemobMedel.getHuanxinUrl() + "/users", JSONObject.toJSON(user), getToken());
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

    /**
     * @return boolean
     */
    @Override
    public boolean chatmessages() {

        Map map = new HashMap();
        try {
            List<BasicNameValuePair> formparams = new ArrayList();
            String url = easemobMedel.getHuanxinUrl() + "/chatmessages?limit=1";
            return HttpUtil.getResult(HttpUtil.executionGET(url, formparams, getToken()));
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

    /**
     * 删除IM用户[单个]
     * @param username 删除的用户
     */
    @Override
    public boolean delUser(String username) {

        try {
            return HttpUtil.getResult(HttpUtil.executionDel(easemobMedel.getHuanxinUrl() + "/users/" + username, getToken()));
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

    /**
     * 重置IM用户密码
     * @param newpassword 新密码
     * @param username 当前用户
     */
    @Override
    public boolean resetUserPassword(String username, String newpassword) {

        JSONObject param = new JSONObject();
        param.put("newpassword", newpassword);
        try {
            return HttpUtil.getResult(HttpUtil.executionPost(easemobMedel.getHuanxinUrl() + "/users/" + username + "/password", param, getToken()));
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

    /**
     * 给IM用户添加好友
     * @param username 当前用户
     * @param newUser 好友用户
     */
    @Override
    public boolean addFriend(String username, String newUser) {

        Map map = new HashMap();
        try {
            return HttpUtil.getResult(HttpUtil.executionPost(easemobMedel.getHuanxinUrl() + "/users/" + username + "/contacts/users/" + newUser,
                                                             HttpUtil.getBasicNameValuePair(map), getToken()));
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

    /**
     * @param username 当前用户
     * @param newUser 好友用户
     * @return boolean
     */
    @Override
    public boolean delFriend(String username, String newUser) {

        Map map = new HashMap();
        try {
            return HttpUtil
                .getResult(HttpUtil.executionDel(easemobMedel.getHuanxinUrl() + "/users/" + username + "/contacts/users/" + newUser, getToken()));
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

    @Override
    public boolean transmissionMessageByone(String username, String message, String type, String messageType) {

        JSONObject param2 = new JSONObject();
        if (!message.contains("code")) {
            message = message;
        } else {
            // param2.put("code", DataContants.ADD_FRI);
            Map mapResult = JSON.parseObject(message, HashMap.class);
            message = ObjectUtils.toString(mapResult.get("message"), "");
        }
        if (StringUtils.isEmpty(messageType)) {
            messageType = MessageWTType.PT.getValue();
        }
        param2.put("code", messageType);
        JSONObject param = new JSONObject();
        param.put("target_type", "users");
        JSONArray list = new JSONArray();

        String[] s = username.split(",");
        for (int i = 0; i < s.length; i++) {
            Object o = s[i];
            if (o != null)
                list.add(o.toString().replaceAll("'", ""));
        }
        param.put("target", list);

        JSONObject param1 = new JSONObject();
        param1.put("type", type);
        // param1.put("action","action1");
        param1.put("msg", message);
        param.put("msg", param1);
        param.put("ext", param2);
        // param.put("from", "admin");
        try {
            return HttpUtil.getResult(HttpUtil.executionPost(easemobMedel.getHuanxinUrl() + "/messages", param, getToken()));
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

    @Override
    public void transmissionMessageFromOneToOne(String fromone, String username, String message, String type, String messageType, Object... values) {

        JSONObject param2 = new JSONObject();
        if (!message.contains("code")) {
            message = message;
        } else {
            // param2.put("code", DataContants.ADD_FRI);
            Map mapResult = JSON.parseObject(message, HashMap.class);
            message = ObjectUtils.toString(mapResult.get("message"), "");
        }

        if (StringUtils.isEmpty(messageType)) {
            messageType = MessageWTType.PT.getValue();
        }
        param2.put("code", messageType);
        JSONObject param = new JSONObject();
        param.put("target_type", "users");
        JSONArray list = new JSONArray();

        String[] s = username.split(",");
        for (int i = 0; i < s.length; i++) {
            Object o = s[i];
            if (o != null)
                list.add(o.toString().replaceAll("'", ""));
        }
        param.put("target", list);

        JSONObject param1 = new JSONObject();
        param1.put("type", type);
        // param1.put("action","action1");
        param1.put("msg", message);

        param.put("msg", param1);
        param.put("ext", param2);

        System.out.println("HuanXin msg Title before encrypt:" + fromone);

        fromone = " wtp64_" + fromone;
        fromone = "String64_" + Base64CoderUtil.encodeString(fromone);
        param.put("from", fromone);

        System.out.println("HuanXin msg:" + message + "title:" + fromone + "UserName:" + username + "HuanXin message Type:" + type
            + "Biz message Type:" + messageType);
        System.out.println("HuanXin msg decode:" + Base64CoderUtil.decodeString(fromone.replace("String64_", "")));
        try {
            HttpUtil.executionAsycPost(easemobMedel.getHuanxinUrl() + "/messages", param, getToken());
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

    @Override
    public void transmissionMessageFromOneToOne(String fromone, String username, String message, String type, String messageType, List listParam) {

        JSONObject param2 = new JSONObject();
        if (!message.contains("code")) {
            message = message;
        } else {
            // param2.put("code", DataContants.ADD_FRI);
            Map mapResult = JSON.parseObject(message, HashMap.class);
            message = ObjectUtils.toString(mapResult.get("message"), "");
        }
        if (StringUtils.isEmpty(messageType)) {
            messageType = MessageWTType.PT.getValue();
        }
        param2.put("code", messageType);
        Map mapResult = new HashMap();
        for (int i = 0; i < listParam.size(); i++) {
            Map map = (Map) listParam.get(i);
            mapResult.put(map.get("code").toString(), map.get("value"));
        }
        param2.put("attributeJson", JSONObject.toJSONString(mapResult));

        JSONObject param = new JSONObject();
        param.put("target_type", "users");
        JSONArray list = new JSONArray();
        String[] s = username.split(",");
        for (int i = 0; i < s.length; i++) {
            Object o = s[i];
            if (o != null)
                list.add(o.toString().replaceAll("'", ""));
        }
        param.put("target", list);
        JSONObject param1 = new JSONObject();
        param1.put("type", type);
        // param1.put("action","action1");
        param1.put("msg", message);
        param.put("msg", param1);
        param.put("ext", param2);
        param.put("from", fromone);
        try {
            HttpUtil.executionAsycPost(easemobMedel.getHuanxinUrl() + "/messages", param, getToken());
        } catch (ClientProtocolException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        } catch (IOException e) {
            throw new BaseException(HuanXianError.ERROR1.getValue(), e.getMessage());
        }
    }

}
